package com.tte.common.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * Lambda多线程实现
 * @Author: DongWH
 * @Date: 2022/11/2 21:33
 */
@Component
public class LambdaThread {
    @Autowired
    @Qualifier("taskPool")
    private Executor threadPool;


    public static void main(String[] args) {
        LambdaThread lambdaThread = new LambdaThread();
        lambdaThread.test();
    }

    //@Scheduled(fixedRate = 2000)
    public void test(){
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                //业务代码
                try {
                    System.out.println("测试线程池调用" + Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public void test1(){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务.");
            }
        };
        executor.execute(runnable);
    }


    /**
     * @ClaseName: LambdaThread
     * @Description: ()里面是函数的参数，中间是箭头， {}是函数的代码块，{}包含了函数的执行以及返回结果。
     * ()->{}
     * @return:
     */
    public void test2() {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        executor.execute(() -> {
            System.out.println("执行任务.");
        });
        executor.shutdown();
    }

    public void call1(){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        executor.submit(new Callable<String>() {
            @Override
            public String call()  {
                System.out.println("执行异步任务.");
                return "异步结果";
            }
        });
        executor.shutdown();
    }

    public void call2(){
        try {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        Future<String> future = executor.submit(() -> {
            System.out.println("执行异步任务.");
            return "异步结果";
        });

            String result = future.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }



}
